package cn.sylinx.horm.util;

import java.util.Arrays;

/**
 * 元组对象
 * 
 * @author han
 *
 */
public class Tuple {

    /**
     * 创建Tuple对象
     * 
     * @param args Object 对象
     * @return the Tuple
     */
    public static Tuple apply(Object... args) {
        return new Tuple(args);
    }

    /**
     * 数组对象
     */
    private Object[] items;

    /**
     * 构造器
     * 
     * @param items Object对象数组
     */
    public Tuple(Object[] items) {
        this.items = items;
    }

    public Tuple() {
    }

    public Object[] getItems() {
        return items;
    }

    public void setItems(Object[] items) {
        this.items = items;
    }

    /**
     * 获取对象
     * 
     * @param index 索引
     * @return Object对象
     */
    public Object get(int index) {
        if (index < 0 || items == null || index > items.length - 1) {
            return null;
        }

        return items[index];
    }

    /**
     * get the object for the index
     * 
     * @param index index
     * @return Object
     */
    @SuppressWarnings("unchecked")
    public <T> T getObject(int index) {
        Object obj = get(index);
        return (T) obj;
    }

    @SuppressWarnings("unchecked")
    public <T> T getObject(int index, Class<T> clz) {
        Object obj = get(index);
        return (T) obj;
    }

    /**
     * get the length
     * 
     * @return the length of the tuple
     */
    public int length() {
        return items == null ? 0 : items.length;
    }

    @Override
    public String toString() {
        return "Tuple [items=" + toStringExt() + "]";
    }

    private String toStringExt() {

        if (items == null)
            return "null";

        int iMax = items.length - 1;
        if (iMax == -1)
            return "[]";

        StringBuilder b = new StringBuilder();
        b.append('[');
        for (int i = 0;; i++) {

            if (items[i] == null) {
                b.append("null");
            } else if (items[i].getClass().isArray()) {
                b.append(Arrays.toString((Object[]) items[i]));
            } else {
                b.append(String.valueOf(items[i]));
            }

            if (i == iMax)
                return b.append(']').toString();
            b.append(", ");
        }
    }
}
